package com.base.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.base.domain.SysMenu;
import com.base.enums.DeletedEnum;
import com.base.mapper.SysMenuMapper;
import com.base.service.SysMenuService;
import com.base.utils.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author gxd
 * @since 2025/6/6
 */
@Slf4j
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    /**
     * 分页列表-菜单列表
     * @param menu 菜单查询条件
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> pageList(SysMenu menu) {
        List<SysMenu> list = this.list(
                Wrappers.lambdaQuery(SysMenu.class)
                        .eq(SysMenu::getDeleted, DeletedEnum.NO.getCode())
                        .like(StrUtil.isNotBlank(menu.getMenuName()), SysMenu::getMenuName, menu.getMenuName())
                        .eq(ObjUtil.isNotNull(menu.getStatus()), SysMenu::getStatus, menu.getStatus())
                        .orderByAsc(SysMenu::getParentId, SysMenu::getSort)
        );
        return list;
    }


    /**
     * 添加或删除-菜单信息
     * @param menu 菜单实体
     * @return 菜单信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public SysMenu addOrEdit(SysMenu menu) {
        Assert.notNull(menu, "菜单信息不能为空");
        if (ObjUtil.isNotNull(menu.getId())) {
            SysMenu menuInfo = Assert.notNull(this.getById(menu.getId()), "要修改的菜单记录不存在");
            BeanUtils.copyNotEmptyProperties(menu, menuInfo);
            this.updateById(menuInfo);
            return menuInfo;
        }

        menu.setDeleted(DeletedEnum.NO.getCode());
        this.save(menu);
        return menu;
    }
}
